<template>
    <div class="imgWrap" ref="imgWrapperRef">
    <!-- {{ api.shapes }} -->
      <!-- <ZoomContainer ref="zoomRef" :controlled="true" :filter="filter" v-bind="zoom" :onZoom="handleZoom"> -->
      <svg ref="svgRef" class="canvas" :style="dimension.svg">
        <Segmentation
          ref="segmentationRef"
          :shapes="api.shapes"
          :offset="offsetBbox"
          @change="handleShapesChange"
          :scale="dimension.scale"
          :transformZoom="transformZoom"
          :updateState="updateState"
          :setCurAnnotation="setCurAnnotation"
          :currentAnnotationId="state.currentAnnotationId"
        ></Segmentation>
      </svg>
      <!-- :currentAnnotationId="state.currentAnnotationId" -->
      <!-- </ZoomContainer> -->
    </div>
  </template>
  <script setup>
  import { defineComponent, ref, reactive, onMounted, toRefs, createVNode, defineExpose } from "vue";
  import Segmentation from "./segmentation/index.vue";
//   import { event as d3Event } from "d3-selection";
  import ZoomContainer from "@/components/ZoomContainer";
  import { useBrush, useZoom, unref, useImage } from "@/hooks";
  import {
    getBounding,
    raise,
    replace,
    extent2Bbox,
    parsePolygon2Bbox,
    getZoomPosition,
  } from "@/utils";
  const segmentationRef = ref(null);
  const {
    brush,
    onBrushStart,
    onBrushMove,
    updateBrush,
    getExtent,
    // onBrushEnd,
    onBrushReset,
  } = useBrush();
  const props = defineProps({
    state: Object,
    currentImg: {
      type: Object,
      default: () => null,
    },
    drawShapeEnd: Function,
    createLabel: Function,
    queryLabels: Function,
    getLabelName: Function,
    updateState: Function,
    handleConfirm: Function,
    deleteAnnotation: Function,
    isTrack: Boolean,
    isSegmentation: Boolean,
    annotationType: String,
  });
  const {
    drawShapeEnd,
    state,
    createLabel,
    queryLabels,
    updateState,
    deleteAnnotation,
    handleConfirm,
    isSegmentation,
    annotationType,
  } = props;
  const zoomRef = ref(null);
  const imgWrapperRef = ref(null);
  
  const api = reactive({
    annotations: props.state.annotations,
    shapes: props.state.shapes,
    label: {}, // 一个页面当前只能存在一个标签
    bounding: null, // 容器位置信息
    isCenter: false, // 图片是否已居中
    imgBounding: null, // 图片的位置，给 bbox 位置定位使用
    active: "", // 当前选中
  });
  const svgRef = ref(null);
  // 标注偏移
  const transformer = reactive({
    id: undefined,
    dx: 0,
    dy: 0,
    x: undefined,
    y: undefined,
  });
  
  // 画布数据
  const dimension = ref({
    svg: {
      width: "800px",
      height: "600px",
    },
    scale: 1,
  });
  
  const initialZoom = {
    zoom: unref(state.zoom),
    zoomX: unref(state.zoomX),
    zoomY: unref(state.zoomY),
  };
  
  const filter = () => {
    // 如果没有开启选框
    // if (!state.selection.value) return true
    // 不允许通过鼠标拖拽来更改缩放
    return d3.event.type !== "mousedown";
  };
  // 更新标注偏移
  const setTransformer = (params) => {
    Object.assign(transformer, params);
  };
  // 转换 zoom 位置
  const transformZoom = (point) => {
    return getZoomPosition(imgWrapperRef.value, point);
  };
  // 开始绘制
  // const handleBrushStart = start => {
  //   const { x, y } = start;
  //   onBrushStart({ x, y });
  // };
  // 选中标注
  const setCurAnnotation = (annotation = {}) => {
    updateState({
      currentAnnotationId: annotation.id || ""
    });
  };
  const handleBrushMove = (state) => {
    const { x, y } = state.end || {};
    onBrushMove({ x, y });
  };
  
  // 基于检测生成 bbox
  const offsetBbox = (bbox) => {
    const paddingLeft =
      dimension.value.scale < 1 && !isNil(api.imgBounding) ? api.imgBounding[0] : 0;
  
    const paddingTop =
      dimension.value.scale < 1 && !isNil(api.imgBounding) ? api.imgBounding[1] : 0;
  
    const pos = {
      x: bbox.x * dimension.value.scale + paddingLeft,
      y: bbox.y * dimension.value.scale + paddingTop,
    };
  
    if (bbox.width && bbox.height) {
      Object.assign(pos, {
        width: bbox.width * dimension.value.scale,
        height: bbox.height * dimension.value.scale,
      });
    }
  
    return pos;
  };
  
  // 标注偏移
  const offset = (annotate) => {
    const { data = {} } = annotate;
    const _bbox = isSegmentation
      ? parsePolygon2Bbox(data.points)
      : extent2Bbox(data.extent);
    return offsetBbox(_bbox);
  };
  const handleShapesChange = ({ type, state: shapeState, options = {} }) => {
    
    const { shape, event } = options;
    switch (type) {
      case "DRAW_END": {
        // 更新当前选中的 shape
        // event &&
        //   showTooltip(shape, event, {
        //     el: imgWrapperRef.value
        //   });
        // 回调，进行标注格式组装
        drawShapeEnd(shape);
        break;
      }
      default: {
        const { transformer } = segmentationRef.value;
        // 更新transformer
        setTransformer(transformer);
        updateState({
          shapes: shapeState.shapes,
        });
      }
    }
    api.shapes = state.shapes;
  };
  const removeData = (shapes) => {
    updateState({
      shapes: shapes,
      history: shapes
    });
    setTimeout(() => {
      segmentationRef.value.removeData(shapes);
    }, 100)
  }
  defineExpose({
    removeData
  })
  </script>
  <style>
  .canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 600px;
  }
  </style>
  